<template>
  <draggable-resizable
    :key="background.id"
    :ref="'ref-element-' + background.id"
    :w="layouts.width"
    :h="layouts.height"
    :z="0"
    :draggable="false"
    :resizable="false"
    :parent="true"
    :deselect-element="deselectElement"
    @activated="onActivated"
    @deactivated="onDeactivated"
  >
    <div class="background" :style="{backgroundColor: background.color || '#fff'}">
      <!-- 背景图片 -->
      <el-image v-if="background.image" fit="cover" :src="background.image + '?x-oss-process=image/interlace,1,image/format,webp'"></el-image>
    </div>
  </draggable-resizable>
</template>

<script>
import { STORE_NAMESPACE } from '../../../../config'
import DraggableResizable from '../draggable-resizable'
// const { DraggableResizable } = require("../../components/index.js")
export default {
  name: 'DesignCanvasBackground',
  components: {
    DraggableResizable
  },
  props: {
    layouts: {
      type: Object,
      default: () => ({})
    },
    // 取消选中的容器选择器
    deselectElement: {
      type: String,
      default: null
    }
  },
  computed: {
    background () {
      return this.layouts.background
    }
  },
  created () {
    // 设置图层方法
    this.$bus.on('bus-design-element-event', this.onBusElementEvent)
  },
  beforeDestroy () {
    this.$bus.off('bus-design-element-event', this.onBusElementEvent)
  },
  methods: {
    // 获取图层组件，执行回调方法
    onBusElementEvent ({id, callback}) {
      if (callback) {
        // 找到ref给回调函数，调用对应组件方法
        const refs = this.$refs[`ref-element-${id}`]
        if (Object.prototype.toString.call(refs) === '[object Object]') {
          refs && callback(refs)
        } else {
          refs && callback(refs[0])
        }
      }
    },
    // draggable-resizable组件再次激活时, 此方法非生命周期方法
    onActivated () {
      this.$store.dispatch(`${STORE_NAMESPACE}/setCurrent`, this.background)
    },
    // draggable-resizable组件再次停用时, 此方法非生命周期方法
    onDeactivated () {
      this.$store.dispatch(`${STORE_NAMESPACE}/setCurrent`, null)
    }
  }
}
</script>

<style lang="less" scoped>
.background{ width: 100%; height: 100%; }
</style>